﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
using System.Xml;
using Microsoft.Xrm.Sdk;
using SolutionExtender.DelegatesHelpers;
using SolutionExtender.Interfaces;
using SolutionExtender.Plugins;
using SolutionExtender;

namespace SolutionExtender.Controls
{
    public partial class ImportControl : UserControl
    {
        #region Variables

        /// <summary>
        /// IOrganization service for CRM Data access
        /// </summary>
        private readonly IOrganizationService _service;

        /// <summary>
        /// List of items to proceed
        /// </summary>
        private readonly XmlNodeList _itemsToProceed;

        /// <summary>
        /// List of results of the import process
        /// </summary>
        private List<ImportResult> _results; 
        
        private readonly PluginManager _pManager;

        #endregion Variables

        #region Constructor

        /// <summary>
        /// Initializes a new instance of class ImportControl
        /// </summary>
        /// <param name="itemsToProceed">List of items to proceed</param>
        /// <param name="pManager"> </param>
        /// <param name="service">IOrganization service for CRM Data access</param>
        public ImportControl(XmlNodeList itemsToProceed, PluginManager pManager, IOrganizationService service)
        {
            InitializeComponent();

            _itemsToProceed = itemsToProceed;
            _service = service;
            _results = new List<ImportResult>();
            _pManager = pManager;
        }

        #endregion Constructor

        #region Methods

        private void ImportControlLoad(object sender, EventArgs e)
        {
            var bg = new BackgroundWorker {WorkerReportsProgress = true};
            bg.DoWork += BgDoWork;
            bg.ProgressChanged += BgProgressChanged;
            bg.RunWorkerCompleted += BgRunWorkerCompleted;
            bg.RunWorkerAsync();
        }

        void BgProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            pbStats.Value = e.ProgressPercentage;
        }

        void BgDoWork(object sender, DoWorkEventArgs e)
        {
            var i = 0;
            foreach(XmlNode node in _itemsToProceed)
            {
                i++;

                var pluginConnector = _pManager.Plugins.Find(p => p.Name == node.Name + "Connector");
                var connector = (IConnector)PluginManager.CreateInstance(pluginConnector.AssemblyPath, pluginConnector.FullName, new object[] { _service });

                if (connector != null)
                {
                    try
                    {
                        LabelDelegates.SetText(lblItemProcessed,
                                              string.Format("Importing {0} : {1}", connector.ObjectName, connector.GetRecordName(node)));
                        var results = connector.Import(node);

                        if (results != null)
                        {
                            _results.AddRange(results);
                        }
                        else
                        {
                            _results.Add(new ImportResult
                                {
                                    Message = string.Empty,
                                    Succeed = true,
                                    Type = connector.ObjectName,
                                    Name = connector.GetRecordName(node)
                                });
                        }
                    }
                    catch (Exception error)
                    {
                        _results.Add(new ImportResult
                                         {
                                             Message = error.Message,
                                             Succeed = false,
                                             Type = connector.ObjectName,
                                             Name = connector.GetRecordName(node)
                                         });
                    }
                }

                ((BackgroundWorker) sender).ReportProgress(i*100/_itemsToProceed.Count);
            }
        }

        void BgRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            lblHeader.Text = "Import complete!";

            foreach(var result in _results)
            {
                var item = new ListViewItem(result.Type);
                item.SubItems.Add(result.Name);
                item.SubItems.Add(result.Succeed ? "Imported" : "Error");
                item.SubItems.Add(result.Message);

                if(!result.Succeed)
                {
                    item.ForeColor = Color.Red;
                }

                lvResults.Items.Add(item);
            }

            pnlComplete.Visible = true;
            pnlImport.Visible = false;
        }

          private void PictureBox1Click(object sender, EventArgs e)
        {
            Process.Start("http://mscrmtools.blogspot.com");
        }

        private void PictureBox2Click(object sender, EventArgs e)
        {
            Process.Start("http://www.javista.com");
        }
        
        #endregion Methods
    }
}
